//
//  SignInView.swift
//  ClassManager
//
//  Created by wqh on 1/27/21.
//

import SwiftUI
import AVFoundation
import CarBode

struct SignInView: View {
    @EnvironmentObject var UserData: CoreData
    @Environment(\.presentationMode) var Presentation
    @State var Index: Int
    @State var timer = Timer.TimerPublisher(interval: 5, runLoop: .current, mode: .default).autoconnect()
    @State var now = Date().timeIntervalSince1970
    @State var changeTo = _state.succeded
    @State var isFailed = false
    @State var allowedBLE = UserDefaults.standard.bool(forKey: "BLE.configured")
    var body: some View {
        if UserData.events[Index].state == 0 {
            Presentation.wrappedValue.dismiss()
        }
        
        return NavigationView {
            VStack(alignment: .center) {
                if Int(5-(now - UserData.events[Index].start)/60) != 0 {
                Text("应在\(Int(5-(now - UserData.events[Index].start)/60))分钟内签到")
                    .font(.title)
                }
                else {
                    Text("应立即签到")
                        .font(.title)
                }
                if isFailed {
                    Text("请再试一次")
                        .foregroundColor(.red)
                        .font(.title)
                }
                if allowedBLE {
                    VStack(spacing: 50) {
                        Image(systemName: "wave.3.backward")
                            .resizable()
                            .scaledToFill()
                            .frame(width: 100, height: 100)
                            .padding()
                        Text("无线打卡已启用，二维码打卡已禁用")
                            .font(.title)
                        HStack {
                            Text("请在手机上点击签到按钮，正在扫描...")
                                .font(.title2)
                            ProgressView()
                                .progressViewStyle(CircularProgressViewStyle())
                        }
                    }
                    .padding(.top, 50)
                }
                Spacer()
                    .onReceive(timer) { _ in
                        now = Date().timeIntervalSince1970
                        if 5-Int((now - UserData.events[Index].start)/60) < 0 && changeTo != .warning {
                            UserData.changeeventState(at: Index, to: .failed)
                            timer.upstream.connect().cancel()
                            Presentation.wrappedValue.dismiss()
                        }
                    }
                if !allowedBLE {
                    ReCBBarcodeView(index: Index)
                        .environmentObject(UserData)
                }
            }.navigationBarTitle("\(UserData.classes[UserData.events[Index]._class].name) - \(UserData.events[Index].techer)")
        }
    }
}

struct ReCBBarcodeView: View {
    @Environment(\.presentationMode) var presentation
    @EnvironmentObject var UserData: CoreData
    @State var index: Int
    var body: some View {
//        print(UserData.events[index].start.string()+UserData.events[index].end.string())
        return NavigationView {
            CBBarcodeView(data: .constant("\(Double(UserData.events[index].start+UserData.events[index].end))"),
                          barcodeType: .constant(.qrCode),
                          orientation: .constant(.up)) { _ in }
                .frame(width: 300, height: 300)
                .navigationTitle("请扫描此二维码")
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }
}
